package com.thinkit.directive.components;

import com.thinkit.core.constant.Constants;
import com.thinkit.directive.render.BaseDirective;
import com.thinkit.directive.render.BaseMethod;
import com.thinkit.utils.properties.ThinkItProperties;
import com.thinkit.utils.utils.Checker;
import freemarker.template.Configuration;
import freemarker.template.SimpleHash;
import freemarker.template.TemplateModelException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 指令组件(注册所有的指令组件)
 */
@Component
public class DirectiveComponent {

    @Autowired
    ThinkItProperties thinkItProperties;

    @Autowired
    public void initDirective(Configuration configuration, List<BaseMethod> baseMethods, List<BaseDirective> baseDirectives) throws TemplateModelException {
        Map<String, Object> freemarkerVariables = new HashMap<>();
        if(Checker.BeNotEmpty(baseMethods)){
            for (BaseMethod baseMethod:baseMethods){
                freemarkerVariables.put(baseMethod.getName().getValue(),baseMethod);
            }
        }
        if(Checker.BeNotEmpty(baseDirectives)){
            for (BaseDirective directive:baseDirectives){
                freemarkerVariables.put(directive.getName().getValue(),directive);
            }
        }
        configuration.setSharedVariable(Constants.SERVER, thinkItProperties.getGateway());
        configuration.setAllSharedVariables(new SimpleHash(freemarkerVariables,configuration.getObjectWrapper()));
    }
}
